﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;
using System.Transactions;

namespace AteneoLibri.Account
{
    public partial class RemoveAccount : System.Web.UI.Page
    {

        User user = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = Utility.HttpSessionManager.GetWebUser();
        }

        protected void btnRemoveAccount_Click(object sender, EventArgs e)
        {
            if (user != null)
            {
                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    try
                    {
                        // da fare in transaction scope
                        using (TransactionScope scope = new TransactionScope())
                        {
                            // 1) Remove Recovery codes
                            bool r1 = service.deleteRecoveryCode(user.IdUser);
                            // 2) Remove Messages (UserIdSeller || UserIdPurchaser || WriteBy)
                            bool r2 = service.deleteMessages(user.IdUser);
                            // 3) Remove Sales (UserId)
                            bool r3 = service.deleteSales(user.IdUser);
                            // 4) Remove Books
                            bool r4 = service.deleteBooks(user.IdUser);
                            // 5) Remove User
                            bool r5 = service.deleteUser(user.IdUser);

                            if (r1 && r2 && r3 && r4 && r5)
                            {
                                scope.Complete();
                                // 6) Logout
                                Response.Redirect("~/Logout.aspx");   
                            }
                            else
                            {
                                // errore durante la cancellazione
                                pnlDeleteUserError.Visible = true;
                                btnRemoveAccount.Visible = false;
                            }
                            scope.Dispose();
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    
                }
            }
        }
    }
}